package com.example.administrator.zhongyichou.base;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.example.administrator.zhongyichou.Bean.BaseEventBean;
import com.example.administrator.zhongyichou.activity.MainActivity;
import com.example.administrator.zhongyichou.utils.LogUtils;
import com.example.administrator.zhongyichou.utils.ToastUtil;
import com.example.administrator.zhongyichou.view.LoadingPage;
import com.example.administrator.zhongyichou.net.core.HttpLoader;
import com.example.administrator.zhongyichou.net.listener.ResultListener;
import com.example.administrator.zhongyichou.net.protocol.GsonBaseProtocol;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by lichenyu on 2017/8/13.
 */

public abstract class BaseActivity<T extends GsonBaseProtocol> extends AppCompatActivity {

    private static final String TAG = "BaseActivity";

    protected int w, h;

    protected LoadingPage mLoadingPage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //activity入栈
        LynActivityManager.getScreenManager().pushActivity(this);
        //打印启动的activity类名
        Log.d(TAG, "onCreate: " + LynActivityManager.getScreenManager().currentActivity().getClass().getSimpleName());

        requestWindowFeature(Window.FEATURE_NO_TITLE);

        EventBus.getDefault().register(this);

        mLoadingPage = new LoadingPage(this) {
            @Override
            protected boolean requestNetWorkData() {
                return isRequestData();
            }

            @Override
            public View createSuccessView() {
                View view = View.inflate(BaseActivity.this, initContentView(), null);
                return view;
            }

            @Override
            public void loadData() {
                requestData();
            }
        };
        mLoadingPage.showHead(isTitle());
        setContentView(mLoadingPage);
        init();
        WindowManager manage = getWindowManager();
        Display display = manage.getDefaultDisplay();
        w = display.getWidth();
        h = display.getHeight();
    }

    /*
    * 隐藏键盘
    *
    * */
    public void hideKeyboard(View v) {
        InputMethodManager imm = ((InputMethodManager) this.getSystemService(this.INPUT_METHOD_SERVICE));
        if (imm != null && this.getCurrentFocus() != null) {
            imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    //获取状态栏高度
    public int getStatusBarHeight() {
        int result = 0;
        if (Build.VERSION.SDK_INT >= 19) {
            result = 0;
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = getResources().getDimensionPixelSize(resourceId);
            }
        }
        return result;
    }

    //获取状态栏高度
    public static int getStaticStatusBarHeight(Context activity) {
        int result = 0;
        if (Build.VERSION.SDK_INT >= 21) {
            result = 0;
            int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = activity.getResources().getDimensionPixelSize(resourceId);
            }
        }
        return result;
    }

    /**
     * 退出所有activity
     */
    public void finishBase() {
        LynActivityManager.getScreenManager().removeAllActivity();
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //将当前activiy弹出栈
        LynActivityManager.getScreenManager().popActivity(this);
        EventBus.getDefault().unregister(this);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    /**
     * @return true 需要请求网络数据 false 不需要请求网络数据
     */
    protected boolean isRequestData() {
        return false;
    }

    public void requestData() {
        HttpLoader mHttpLoader = initHttpLoader();      //1.创建好Retrofit对象,将协议类传递给HttpLoader,并且将HttpLoader类引用传递过来
        setRequestParams(mHttpLoader);                  //2.设置请求参数,将HttpLoader作为参数传递,
        if (mHttpLoader == null)
            return;
        mHttpLoader.executor(new ResultListener<T>() {  //3.执行去请求网络,里面自定义一个接口封装状态
            @Override
            public void success(T mGsonBaseProtocol) {
                mLoadingPage.showSuccessPage();
                try {
                    responseData(mGsonBaseProtocol);
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    mLoadingPage.showEmptyPage();
                    ToastUtil.showToast("内部程序异常");
                    LogUtils.e(e);
                }
            }

            @Override
            public void error(String mErrorProtocal) {
                mLoadingPage.showEmptyPage();
            }

            @Override
            public void notNet() {
                if (mLoadingPage != null)
                    mLoadingPage.showErrorPage();
            }

            @Override
            public void requestError() {
                mLoadingPage.showErrorPage();
            }
        });
    }

    /**
     * 设置参数，如果需要，重写此方法.
     * <p>
     * 传递HttpLoader加载器类
     *
     * @param mHttpLoader
     */
    protected void setRequestParams(HttpLoader mHttpLoader) {

    }


    protected abstract void init();

    /**
     * 具体填充的逻辑有子类实现
     *
     * @param mGsonBaseProtocal
     */
    protected abstract void responseData(T mGsonBaseProtocal) throws NullPointerException;

    /**
     * 子类自己去初始化相应的loader加载器类
     *
     * @return
     */
    protected abstract HttpLoader initHttpLoader();

    protected abstract int initContentView();

    //响应eventbus事件
    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onEvent(BaseEventBean baseEventBean) {
        if (onEventBus(baseEventBean)) {
            EventBus.getDefault().removeStickyEvent(baseEventBean);
        }
    }

    /**
     * @param baseEventBean
     * @return 返回值代表是否移除本次粘性事件
     */
    public abstract boolean onEventBus(BaseEventBean baseEventBean);

    /**
     * activity默认显示失败页面的头
     *
     * @return
     */
    public boolean isTitle() {
        return true;
    }

}
